//
//  WHRootViewController.m
//  BinFengExpressOwner
//
//  Created by 邓伟浩 on 2018/10/12.
//  Copyright © 2018年 BinFeng. All rights reserved.
//

#import "WHRootViewController.h"
#import "UINavigationBar+setBackgroundImage.h"

@interface WHRootViewController ()

@property (nonatomic, assign) int basePage;

@end

@implementation WHRootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = CViewBgMainColor;
    [self initBaseParams];
    
    if (@available(iOS 11.0, *)) {
        [UIScrollView appearance].contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    UINavigationBar *navBar = self.navigationController.navigationBar;
    if (self.naviType == NaviTypeClear) {
        [navBar setClearImage];
        
        if (self.navigationController.viewControllers.count > 1) {
            UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
            backButton.frame = CGRectMake(0, 0, 40, kNavBarHeight);
            [backButton addTarget:self action:@selector(backBtnClicked) forControlEvents:UIControlEventTouchUpInside];
            [backButton setImage:IMAGE_NAMED(@"icon_menu_whiteBack") forState:UIControlStateNormal];
            UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithCustomView:backButton];
            self.navigationItem.leftBarButtonItem = back;
        }
        
    } else {
        [navBar setDefaultImage];
        if (self.navigationController.viewControllers.count > 1) {
            UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
            backButton.frame = CGRectMake(0, 0, 40, kNavBarHeight);
            [backButton addTarget:self action:@selector(backBtnClicked) forControlEvents:UIControlEventTouchUpInside];
            [backButton setImage:IMAGE_NAMED(@"icon_menu_back") forState:UIControlStateNormal];
            UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithCustomView:backButton];
            self.navigationItem.leftBarButtonItem = back;
        }
    }
}

- (void)initBaseParams {
    _basePage = 1;
    _baseDataArray = @[].mutableCopy;
}

/** 懒加载UITableView */
- (UITableView *)baseTableView {
    if (!_baseTableView) {
        _baseTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _baseTableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
        _baseTableView.estimatedRowHeight = 0;
        _baseTableView.estimatedSectionHeaderHeight = 0;
        _baseTableView.estimatedSectionFooterHeight = 0;
        
        //头部刷新
        _baseTableView.mj_header = [WHGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRereshing)];
        
        //底部刷新
        _baseTableView.mj_footer = [WHGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRereshing)];
        
        _baseTableView.tableFooterView = [UIView new];
        _baseTableView.backgroundColor = CViewBgMainColor;
        _baseTableView.separatorColor = CLineColor;
        
        _baseTableView.mj_footer.hidden = YES;
    }
    return _baseTableView;
}

- (WHNetRequestModel *)requestModel {
    return nil;
}

#pragma mark - —————— 下拉刷新 ——————
- (void)headerRereshing {
    WHNetRequestModel *requestModel = [self requestModel];
    
    [self getDataByPageNumber:1 model:requestModel completion:^(BOOL isSucess, BOOL isLast) {
        [self.baseTableView.mj_header endRefreshing];
        if (isSucess) {
            _basePage = 1;
            self.baseTableView.mj_footer.hidden = NO;
            if (isLast) {
                self.baseTableView.mj_footer.hidden = YES;
            } else {
                [self.baseTableView.mj_footer resetNoMoreData];
            }
        }
    }];
    
}

#pragma mark - —————— 上拉刷新 ——————
- (void)footerRereshing {
    WHNetRequestModel *requestModel = [self requestModel];
    
    [self getDataByPageNumber:(_basePage+1) model:requestModel completion:^(BOOL isSucess, BOOL isLast) {
        if (isSucess) {
            if (isLast) {
                [self.baseTableView.mj_footer endRefreshingWithNoMoreData];
            } else {
                _basePage = _basePage + 1;
                [self.baseTableView.mj_footer endRefreshing];
            }
        } else {
            [self.baseTableView.mj_footer endRefreshing];
        }
        
    }];
}

#pragma mark - —————— 方法 ——————

- (void)getDataByPageNumber:(int)pageNumber model:(WHNetRequestModel *)model completion:(void (^)(BOOL isSucess, BOOL isLast))completion {
    NSString *postURL = model.postURL;
    NSMutableDictionary *dict = model.paramDict.mutableCopy;
    [dict setObject:@(pageNumber) forKey:@"pageNum"];
    
    _baseDataTask = [WHNetworkManager requestWithURL:postURL parameters:dict isUpData:YES Success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if (ValidDict(responseObject)) {
            NSNumber *errCode = responseObject[@"errcode"];
            NSString *errorMsg = responseObject[@"errmsg"];
            if (errCode.intValue == 0) {
                NSDictionary *billDict = responseObject[@"retobj"];
                
                if (pageNumber == 1) {
                    [_baseDataArray removeAllObjects];
                }
                
                NSArray *messageArray = billDict[@"data"];
                if (messageArray.count == 0) {
                    if (completion) {
                        [_baseTableView reloadData];
                        completion(YES, YES);
                    }
                    if (pageNumber == 1) {
                        DLog(@"没有数据");
                        [self showNoDataView];
                    }
                    
                    return;
                }
                [self hideNoDataView];
                
                NSArray *tempMessageArray = [NSArray modelArrayWithClass:[model.modelClass class] json:messageArray];
                [_baseDataArray addObjectsFromArray:tempMessageArray];
                [_baseTableView reloadData];
                
                
                if (completion) {
                    completion(YES, NO);
                }
            } else {
                [WHView showHudMsg:errorMsg];
                if (completion) {
                    completion(NO, NO);
                }
            }
        }
    } failure:^(NSError *error) {
        if (completion) {
            completion(NO, NO);
        }
    }];
}

- (void)showNoDataView {
    
}

- (void)hideNoDataView {
    
}

- (void)addNavigationItemWithImageNames:(NSArray *)imageNames isLeft:(BOOL)isLeft target:(id)target action:(SEL)action tags:(NSArray *)tags {
    NSMutableArray * items = [[NSMutableArray alloc] init];
    NSInteger i = 0;
    for (NSString * imageName in imageNames) {
        UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
        btn.frame = CGRectMake(0, 0, 30, 30);
        [btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
        
        btn.tag = [tags[i++] integerValue];
        UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithCustomView:btn];
        [items addObject:item];
        
    }
    if (isLeft) {
        self.navigationItem.leftBarButtonItems = items;
    } else {
        self.navigationItem.rightBarButtonItems = items;
    }
}

- (void)backBtnClicked {
    if (_baseDataTask) {
        [_baseDataTask cancel];
        _baseDataTask = nil;
    }
    
    if (self.presentingViewController) {
        [self dismissViewControllerAnimated:YES completion:nil];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)dealloc {
    DLog(@"=====释放%@=====", [self class]);
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return self.naviType == NaviTypeClear?UIStatusBarStyleLightContent:UIStatusBarStyleDefault;
//    return UIStatusBarStyleDefault;
}

@end
